package no.truben.kroken.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import no.truben.kroken.Archive;

public class PluginReader {
	
	public static Map<String, Archive> readPlugins(String path) {
		Map<String, Archive> m = new HashMap<String, Archive>();
		File pluginDir = new File(path);
		for(File f: pluginDir.listFiles()) {
			if(f.getAbsolutePath().endsWith(".plugin")) {
				Archive a = readFile(f);
				System.out.println(a);
				m.put(a.getExtension(), a);
			}
		}
		return m;
	}
	
	private static Archive readFile(File f) {
		Archive a = new Archive();
		try {
			Scanner s = new Scanner(f);
			while(s.hasNextLine()) {
				String line = s.nextLine();
				if(line.indexOf(":=")>0) {
					
					String[] property = readLine(line);
					
					if(property[0].equals("author"))
						a.setAuthor(property[1]);
					else if(property[0].equals("description")) {
						a.setDescription(property[1]);
					}
					else if(property[0].equals("exstension")) {
						a.setExtension(property[1]);
					}
					else if(property[0].equals("path")) {
						a.setPath(property[1]);
					}
				}
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return a;
	}
	
	private static String[] readLine(String line) {
		String property[] = line.split(":=");
		property[0] = property[0].toLowerCase();
		return property;
	}
}
